import Koa from 'koa';
import Router from '@koa/router';
import cors from '@koa/cors';
import bodyParser from 'koa-bodyparser';
import { WechatferryAgent } from '@wechatferry/agent'

const app = new Koa();
const router = new Router();

const wxAgent = new WechatferryAgent();

// 启用跨域
app.use(cors());

// 解析请求体
app.use(bodyParser());

// 返回值
// 成功
const responseSuccess = (data = '') => ({
  errno: 0,
  errmsg: '',
  data
});

const responseFail = (errno = 0, errmsg = '系统错误', data = '') => ({
  errno,
  errmsg,
  data
})
// 失败
// 查找微信联系人
const findWxUser = (nickname, wxid) => {
  // 通过联系人查询
  const userList = wxAgent.getContactList();
  /*
    {
      nickName: 'Mr.Zhou',
      userName: 'wxid_8037620376',
      remark: 'Zhou 潍坊 生财',
      alias: 'Zhoujingxi',
      pinYinInitial: '?MRZHOU',
      remarkPinYinInitial: '?MRZHOUWFSC',
      labelIdList: '18',
      smallHeadImgUrl: 'https://wx.qlogo.cn/mmad/v',
      tags: [ '18' ]
    } 
  */
  const index = userList.findIndex(u => u.alias.toLowerCase() == wxid.toLowerCase() || u.remark == nickname);
  // console.log(index);
  if (index >= 0) return userList[index];
  return null;
}

// 接口测试
router.get('/api/status', async (ctx) => {
    ctx.body = responseSuccess('ok');
})

// 提醒单个组员打卡
router.post('/api/remindOne', async (ctx) => {
  const data = ctx.request.body;
  const { nickname, wxid, text = '你好' } = data;
  const wxContact = findWxUser(nickname, wxid);
  if (wxContact && wxContact.userName) {
    const {userName, remark} = wxContact;
    wxAgent.sendText(userName, text);
    ctx.body = responseSuccess(remark + ' >> 发送成功');
    console.log('成功发送', data, wxContact);
    return;
  }
  
  console.log('未成功', data, wxContact);
  ctx.body = responseFail(1, '发送失败');
});


// 路由
app.use(router.routes()).use(router.allowedMethods());

// 启动
const PORT = 3000;
app.listen(PORT, () => {
    wxAgent.start()
    console.log(`API服务已启动，端口：${PORT}`);
});